package com.googlecode.tidej.client.tree;

import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.event.logical.shared.SelectionHandler;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.Tree;
import com.google.gwt.user.client.ui.TreeItem;
import com.googlecode.tidej.client.TidejController;
import com.googlecode.tidej.shared.model.Artifact;
import com.googlecode.tidej.shared.model.Library;
import com.googlecode.tidej.shared.model.Model;
import com.googlecode.tidej.shared.model.Operation;
import com.googlecode.tidej.shared.model.Property;
import com.googlecode.tidej.shared.model.Type;


public class ClassTreeOld extends Composite {

  TidejController controller;
  Tree tree = new Tree();
  ScrollPanel scrollPanel = new ScrollPanel(tree);
  
  public ClassTreeOld(TidejController controller) {
    this.controller = controller;
    refresh(true);
    initWidget(scrollPanel);
  }
  
  
  private TreeItem createTypeItem(Type type) {
    TreeItem item = new TreeItem(type.getName());
    item.setUserObject(type);
    for (Property p: type.getOwnProperties()) {
      TreeItem child = new TreeItem(p.toString());
      child.setUserObject(p);
      item.addItem(child);
    }
    for (Operation o: type.getOwnOperations()) {
      TreeItem child = new TreeItem(o.toString());
      child.setUserObject(o);
      item.addItem(child);
    }
    return item;
  }
  
  private TreeItem createLibraryItem(Library library) {
    TreeItem item = new TreeItem(library.getName());
    item.setUserObject(library);
    for (Type t: library.getTypes()) {
      item.addItem(createTypeItem(t));
    }
    return item;
  }
  
  public void refresh(boolean foo) {
    scrollPanel.remove(tree);
    tree = new Tree();
    tree.addSelectionHandler(new SelectionHandler<TreeItem>() {
      @Override
      public void onSelection(SelectionEvent<TreeItem> event) {
        Object userObject = event.getSelectedItem().getUserObject();
        controller.selected((Artifact) (userObject == null ? controller.getModel() : userObject));
      }
    });
    
    scrollPanel.add(tree);
    
    Model model = controller.getModel();
    if (controller.getProject() != null) {
      TreeItem project = createLibraryItem(controller.getProject());
      tree.addItem(project);
      tree.setSelectedItem(project);
    }
    
    TreeItem item = new TreeItem("Libraries");
    for (Library lib: model.getLibraries()) {
      item.addItem(createLibraryItem(lib));
    }
    tree.addItem(item);
  }


  public void select(Artifact a) {
    // TODO Auto-generated method stub
    
  }
  
}
